<?php
 
	class FileDataEngine
    {
        private $template;
        private $dbProvider;
		
        public function __construct()
        {
            $this->template = new TemplateEngine();
			$this->dbProvider = new UserDataProvider();
		}

        public function saveFile( $email, $firstName, $lastName )
        {
            $isSaved = false;
			$realFileName = "";
			if ( isset( $_FILES['my_file'] ) )
            {
                $uploadedFileInfo = $_FILES['my_file'];
                $tmpFilePath = $uploadedFileInfo['tmp_name'];
                $realFileName = $uploadedFileInfo['name'];
                $saveFilePath = SITE_ROOT . "\\uploaded\\" . $realFileName;
                $isSaved = move_uploaded_file( $tmpFilePath, $saveFilePath );
            }
			if ( $isSaved )
			{
				$this->dbProvider->saveInfoFileInDb( $realFileName, $email, $firstName, $lastName );
				return true;
			}
			else
			{
				throw new Exception( $this->template->convertToHtml( "File was not uploaded!" ) );
				return false;
			}
        }
		
		private function checkSetExtension()
		{
			$isSet = isset( $_GET['extension'] );
			return $isSet;
		} 
		
		private function getExtension( $filename ) 
		{
			return strtolower( substr($filename, strrpos($filename, '.') + 1) );
		}
		
		private function checkSetEmail()
		{
			$isSet = isset( $_GET['userEmail'] );
			return $isSet;
		}
		
		public function getImages()
		{
			$extImg = array( 'jpg', 'jpeg', 'png', 'bmp', 'gif', 'tif' );
			$fileArr = $this->checkFiles();
			$images = array();
			for ( $i = 0; $i < count( $fileArr ); $i++ )
			{
				if ( in_array( $this->getExtension( $fileArr[$i]['name'] ), $extImg ) )
				{
					$images[] = $fileArr[$i]['name'];
				}
			}
			if ( empty($images) )
			{	
				return NULL;
			}
			return $images;
		}

        private function checkFiles()
        {
			$extension = "";
			$email = "";
			$isExt = false;
			$isEmail = false;
			$list = "";
			if( $this->checkSetExtension() && $this->checkSetEmail() )
			{
				$extension = $_GET['extension'];
				$email = $_GET['userEmail'];
				$isExt = ( !empty( $extension ) );
				$isEmail = ( !empty( $email ) );
			}
			$fileList = array();
            if ( is_dir( UPLOAD_DIR ) ) 
            {
                if ( $dir = opendir( UPLOAD_DIR ) ) 
                {               
					$i = 0;
					while ( ( ( $filename = readdir( $dir ) ) !== false ) )
                    {
						$isValid = true;
						if ( ( $filename!="." ) && ( $filename != ".." ) )
                        {
							if ( $isExt )
							{
								$isValid = ( $this->getExtension( $filename ) == $extension );
							}
							if ( $isEmail && $isValid )
							{
								$isValid = ( $this->dbProvider->getEmailByFilename( $filename ) == $email );
							}
							if ( $isValid )
							{
								$fileList[$i]['name'] = $filename;
								$fileList[$i]['fileLink'] = UPLOAD_NAME.$filename;
								$email = $this->dbProvider->getEmailByFilename( $filename );
								if( $email )
								{
									$fileList[$i]['emailLink'] = "get_user_info.php?id=".$this->dbProvider->getUserIdByEmail( $email );
									$fileList[$i]['uploader'] = $email;
									$fileList[$i]['fileId'] = $this->dbProvider->getFileIdByFilename( $filename );
									$fileList[$i]['rating'] = $this->dbProvider->getNewRating( $fileList[$i]['fileId'] );
								}
								else
								{
									$fileList[$i]['uploader'] = "Unknown";
									$fileList[$i]['emailLink'] = "#";
									$fileList[$i]['fileId'] = 0;
									$fileList[$i]['rating'] = 0;
								}
								
								++$i;
							}
                        }
                    }
                    closedir( $dir );
                }
            }
            return $fileList;
        }
		
		public function showFiles()
		{
			$navigation = new NavigationEngine("file", count($this->checkFiles()));
			$page = $navigation->getPage();
			$files = $this->checkFiles();
			$start = ( ( USER_AMOUNT * $page ) - USER_AMOUNT );
			
			if ( $files )
            {
                $i = $start;
				$limit = $start + USER_AMOUNT;
				$list = array();
				
                while ( $i < $limit )
                {
                    if ( ( $i >= count( $files ) ) || ( $i >= $limit ) ) break;
					
					$list[] = $files[$i];
						
                    ++$i;
                }
				$pages = array();
				if ($navigation->getPageNum() == 1)
				{
					$pages = $navigation->printOnePage();
				}
				else if ( $page == 1)
				{
					$pages = $navigation->printFirstPart();
				}
				else if ($page == $navigation->getPageNum() )
				{
					$pages = $navigation->printLastPart();
				}
				else
				{
					$pages = $navigation->printMiddlePart( $page );
				}
				$vars = array( 
								'fileList' => $list,
								'isEmpty' => ( $this->getImages()) ? false : true,
								'pages' => $pages,
							  );
				
				$vars['navigation'] = getView('templates/navigation.tpl', $vars);
				return getView('templates/file_list.tpl', $vars);
            }
			else
			{
				throw new Exception( $this->template->convertToHtml( "These files don't exist!" ) );
			}
		}	
	}
	
?>